use strict;
use warnings;
use lib qw(/home/woeishya/domains/ocfaustralia.org/connect/public_html/cgi-bin);
use Apache::Session::File ();
use CGI::Cookie;
use Data::Dumper;
use Form::Person;
use Form::PersonAndContact;
use Form::FamilyAttendence;
use Form::FriendInvitation;
use Form::ContactDetails;
use Form::NokContact;
use My::Form::Helper::Generator qw(generate_field_html generate_form_elements_html);
use My::Form::Helper::Processor qw(prev_form next_form);
use My::Form::Helper::Tools qw(eval_code evalable_code_from_hash);
my $field_name = 'name';
my %session;
my %cookies = CGI::Cookie->fetch($r);
eval {
	tie %session, 'Apache::Session::File',
		( defined( $cookies{SESSION} ) ? $cookies{SESSION}->value() : undef ),
		{ Directory     => "/home/woeishya/session_data",
		  LockDirectory => "/home/woeishya/session_data"
		};
};

if ( $@ && $@ =~ /^Object does not exist in the data store/ ) {
	tie %session, 'Apache::Session::File', (undef),
		{ Directory     => "/home/woeishya/session_data",
		  LockDirectory => "/home/woeishya/session_data"
		};
}
my $session_cookie =
	new CGI::Cookie( -name => 'SESSION', -value => $session{_session_id}, -expires => '+1y' );
$r->headers_out->add( 'Set-Cookie'    => $session_cookie );
$r->headers_out->add( 'Cache-Control' => 'no-cache' );

# init
$session{'current_form'} = 'family attendence' unless ( $session{'current_form'} );
my $family_form             = Form::FamilyAttendence->new;
my $person_form             = Form::Person->new;
my $person_and_contact_form = Form::PersonAndContact->new;
my $friend_form             = Form::FriendInvitation->new;
my $contact_form            = Form::ContactDetails->new;
my $nok_form                = Form::NokContact->new;
my $forms = {
	'family attendence' => {
		RHTMLO_form     => $family_form,
		session_hashref => \%session,
		next_form =>
			{ perl => '(($family_attending =~ /yes/) ? "personal details" : "friend details")', },
		validate => {
			perl =>
				'( ($family_attending =~ /yes/) && ( ($spouse_attending =~ /yes/) || ($children_attending > 0) ) ) || ($family_attending =~ /no/)',
		},
		elements => [{ text => "Will your family be attending the 50th OCF Convention this year?" },
					 { fieldset => 1,
					   legend   => 'Registration type',
					   elements => [ { field_name => 'family_attendence',
									   label      => 'Family attending',
									   save_to    => 'family_attending',
									 },
					   ],
					 },
					 { fieldset => 1,
					   legend   => 'Family registration',
					   elements => [ { field_name => 'spouse_attendence',
									   label      => 'Spouse attending',
									   save_to    => 'spouse_attending',
									 },
									 { field_name => 'children_attendence',
									   label      => 'Children attending',
									   save_to    => 'children_attending',
									 },
					   ],
					 },
		],
	},
	'friend details' => {
		RHTMLO_form     => $friend_form,
		session_hashref => \%session,
		next_form =>
			{ perl => '(($friends_more =~ /yes/) ? "friend details" : "personal details")', },
		elements => [
			{  fieldset => 1,
			   legend   => 'Friend details',
			   elements => [
				   {  text =>
						  "Would you like to be bunked together with a friend as your roommate? Please enter their details so that we may identify them and allocate the rooms according to your preference."
				   },
				   {  field_name => 'name',
					  label      => 'First Name',
					  save_to    => { perl => 'return "friend_first_name_$form_multiplicity"', },
				   },
				   {  field_name => 'family_name',
					  label      => 'Family Name',
					  save_to    => { perl => 'return "friend_family_name_$form_multiplicity"', },
				   },
				   {  field_name => 'email_address',
					  label      => 'Email Address',
					  save_to    => { perl => 'return "friend_email_address_$form_multiplicity"', },
				   },
				   {  field_name => 'phone_number',
					  label      => 'Phone Number',
					  save_to    => { perl => 'return "friend_phone_number_$form_multiplicity"', },
				   },
				   {  field_name => 'centre_affiliation',
					  label      => 'OCF Centre',
					  save_to    => { perl => 'return "friend_centre_$form_multiplicity"', },
				   },
				   {  text =>
						  "Do you wish to specify additional choices of friends as room mates? Specifying more choices will ensure a higher likelihood of you being bunked with a friend.",
				   },
				   {  field_name => 'more_friends',
					  label      => 'Other choices',
					  tip        => '',
					  save_to    => { perl => 'return "friends_more"', },
				   },
			   ],
			},
		],
	},
	'personal details' => {
		RHTMLO_form     => $person_form,
		session_hashref => \%session,
		next_form       => 'contact details',
		validate        => {
			perl =>
				'($registrant_centre && $registrant_ocf_term) || (!$registrant_centre && !$registrant_ocf_term)',
		},
		elements => [
				   { subheading_text => 'OCF Connect' },
				   { text => 'Please enter the following details to create your personal profile' },
				   { fieldset => 1,
					 legend   => 'Personal Particulars',
					 elements => [ { field_name     => 'name',
									 label          => 'Name',
									 tip            => '<u>Jonathan</u> Tan',
									 compound_field => 0,
									 save_to        => 'registrant_name',
								   },
								   { field_name     => 'family_name',
									 label          => 'Family Name',
									 tip            => 'Jonathan <u>Tan</u>',
									 compound_field => 0,
									 attributes     => {},
									 save_to        => 'registrant_family_name',
								   },
								   { field_name     => 'birth_date',
									 label          => 'Date of Birth',
									 tip            => '',
									 compound_field => 1,
									 class          => 'selection_required',
									 save_to        => 'registrant_dob',
								   },
								   { field_name     => 'birth_country_id',
									 label          => 'Country of Birth',
									 tip            => '',
									 compound_field => 0,
									 class          => 'selection_required',
									 save_to        => 'registrant_birth_country',
								   },
								   { field_name     => 'gender',
									 label          => 'Gender',
									 tip            => '',
									 compound_field => 1,
									 save_to        => 'registrant_gender',
								   },
								   { field_name     => 'nationalities',
									 label          => 'Nationality',
									 tip            => 'May select multiple countries',
									 compound_field => 0,
									 class          => 'selection_required',
									 save_to        => 'registrant_nationalities',
								   },
					 ],
				   },
				   { fieldset => 1,
					 legend   => 'Centre Affiliation',
					 elements => [ { field_name     => 'centre_affiliation',
									 label          => 'OCF Centre',
									 tip            => '',
									 compound_field => 0,
									 save_to        => 'registrant_centre',
								   },
								   { field_name     => 'ocf_service_term',
									 label          => 'Years of participation',
									 tip            => 'ie: 2002-2009',
									 compound_field => 1,
									 save_to        => 'registrant_ocf_term',
								   },
					 ],
				   },
		],
	},
	'contact details' => {
		RHTMLO_form     => $contact_form,
		session_hashref => \%session,
		next_form       => {
			perl =>
				'(($family_attending =~ /yes/) && ($spouse_attending =~ /yes/) ? "spouse details" : ( ($family_attending =~ /yes/) && $children_attending ? "child details" : "NOK" ) )',
		},
		elements => [ {  fieldset => 1,
						 legend   => 'Contact Details',
						 elements => [ {  field_name     => 'email_address',
										  label          => 'Email Address',
										  tip            => '',
										  compound_field => 0,
										  save_to        => 'registrant_email',
									   },
									   {  field_name     => 'phone_number',
										  label          => 'Phone Number',
										  tip            => '',
										  compound_field => 0,
										  save_to        => 'registrant_phone',
									   },
						 ],
					  },
					  {  fieldset => 1,
						 legend   => 'Address Details',
						 elements => [ {  field_name     => 'address_1',
										  label          => 'Address',
										  tip            => '',
										  compound_field => 0,
										  save_to        => 'registrant_address_1',
									   },
									   {  field_name     => 'address_2',
										  label          => '',
										  tip            => '',
										  compound_field => 0,
										  save_to        => 'registrant_address_2',
									   },
									   {  field_name     => 'city',
										  label          => 'City',
										  tip            => '',
										  compound_field => 0,
										  save_to        => 'registrant_city',
									   },
									   {  field_name     => 'state',
										  label          => 'State',
										  tip            => '',
										  compound_field => 0,
										  save_to        => 'registrant_state',
									   },
									   {  field_name     => 'postcode',
										  label          => 'Post Code',
										  tip            => '',
										  compound_field => 0,
										  save_to        => 'registrant_postcode',
									   },
									   {  field_name     => 'country',
										  label          => 'Country',
										  tip            => '',
										  compound_field => 0,
										  save_to        => 'registrant_country',
									   },
						 ],
					  },
		],
	},
	'spouse details' => {
		RHTMLO_form     => $person_and_contact_form,
		session_hashref => \%session,
		next_form       => {
			perl =>
				'(($family_attending =~ /yes/) && $children_attending ? "child details" : "finished")'
		},
		validate => {
			   perl =>
				   '($spouse_centre && $spouse_ocf_term) || (!$spouse_centre && !$spouse_ocf_term)',
		},
		elements => [
			{ subheading_text => 'Spouse Signup' },
			{ text => 'Please enter the following details to complete the signup for your spouse' },
			{  fieldset => 1,
			   legend   => 'Personal Particulars',
			   elements => [ {  field_name     => 'name',
								label          => 'Name',
								tip            => '<u>Tricia</u> Teo',
								compound_field => 0,
								save_to        => 'spouse_name',
							 },
							 {  field_name     => 'family_name',
								label          => 'Family Name',
								tip            => 'Tricia <u>Teo</u>',
								compound_field => 0,
								attributes     => {},
								save_to        => 'spouse_family_name',
							 },
							 {  field_name     => 'birth_date',
								label          => 'Date of Birth',
								tip            => '',
								compound_field => 1,
								class          => 'selection_required',
								save_to        => 'spouse_dob',
							 },
							 {  field_name     => 'birth_country_id',
								label          => 'Country of Birth',
								tip            => '',
								compound_field => 0,
								class          => 'selection_required',
								save_to        => 'spouse_birth_country',
							 },
							 {  field_name     => 'gender',
								label          => 'Gender',
								tip            => '',
								compound_field => 1,
								save_to        => 'spouse_gender',
							 },
							 {  field_name     => 'nationalities',
								label          => 'Nationality',
								tip            => 'May select multiple countries',
								compound_field => 0,
								class          => 'selection_required',
								save_to        => 'spouse_nationalities',
							 },
			   ],
			},
			{  fieldset => 1,
			   legend   => 'Contact Details',
			   elements => [ {  field_name     => 'email_address',
								label          => 'Email Address',
								tip            => '',
								compound_field => 0,
								save_to        => 'spouse_email',
							 },
							 {  field_name     => 'phone_number',
								label          => 'Phone Number',
								tip            => '',
								compound_field => 0,
								save_to        => 'spouse_phone',
							 },
			   ],
			},
			{  fieldset => 1,
			   legend   => 'Centre Affiliation',
			   elements => [ {  field_name     => 'centre_affiliation',
								label          => 'OCF Centre',
								tip            => '',
								compound_field => 0,
								save_to        => 'spouse_centre',
							 },
							 {  field_name     => 'ocf_service_term',
								label          => 'Years of participation',
								tip            => 'ie: 2002-2009',
								compound_field => 1,
								save_to        => 'spouse_ocf_term',
							 },
			   ],
			},
		],
	},
	'child details' => {
		RHTMLO_form     => $person_and_contact_form,
		session_hashref => \%session,
		next_form       => {
			perl =>
				'(($family_attending =~ /yes/) && $form_multiplicity <= $children_attending ? "child details" : "finished")'
		},
		validate => {
			perl =>
				'($registrant_centre && $registrant_ocf_term) || (!$registrant_centre && !$registrant_ocf_term)',
		},
		elements => [
			{  subheading_text => {
				   perl =>
					   'return "Child Signup (" . $form_multiplicity . "/" . $children_attending . ")"'
			   }
			},
			{ text => 'Please enter the following details to complete the signup for your child' },
			{  fieldset => 1,
			   legend   => 'Personal Particulars',
			   elements => [ {  field_name     => 'name',
								label          => 'Name',
								tip            => '<u>Jimmy</u> Tan',
								compound_field => 0,
								save_to => { perl => 'return "child_name_$form_multiplicity"' },
							 },
							 {  field_name     => 'family_name',
								label          => 'Family Name',
								tip            => 'Jimmy <u>Tan</u>',
								compound_field => 0,
								attributes     => {},
								save_to =>
									{ perl => 'return "child_family_name_$form_multiplicity"' },
							 },
							 {  field_name     => 'birth_date',
								label          => 'Date of Birth',
								tip            => '',
								compound_field => 1,
								class          => 'selection_required',
								save_to => { perl => 'return "child_dob_$form_multiplicity"' },
							 },
							 {  field_name     => 'birth_country_id',
								label          => 'Country of Birth',
								tip            => '',
								compound_field => 0,
								class          => 'selection_required',
								save_to =>
									{ perl => 'return "child_birth_country_$form_multiplicity"' },
							 },
							 {  field_name     => 'gender',
								label          => 'Gender',
								tip            => '',
								compound_field => 1,
								save_to => { perl => 'return "child_gender_$form_multiplicity"' },
							 },
							 {  field_name     => 'nationalities',
								label          => 'Nationality',
								tip            => 'May select multiple countries',
								compound_field => 0,
								class          => 'selection_required',
								save_to =>
									{ perl => 'return "child_nationalities_$form_multiplicity"' },
							 },
			   ],
			},
			{  fieldset => 1,
			   legend   => 'Contact Details',
			   elements => [ {  field_name     => 'email_address',
								label          => 'Email Address',
								tip            => '',
								compound_field => 0,
								save_to => { perl => 'return "child_email_$form_multiplicity"' },
							 },
							 {  field_name     => 'phone_number',
								label          => 'Phone Number',
								tip            => '',
								compound_field => 0,
								save_to => { perl => 'return "child_phone_$form_multiplicity"' },
							 },
			   ],
			},
			{  fieldset => 1,
			   legend   => 'Centre Affiliation',
			   elements => [{   field_name     => 'centre_affiliation',
								label          => 'OCF Centre',
								tip            => '',
								compound_field => 0,
								save_to => { perl => 'return "child_centre_$form_multiplicity"' },
							},
							{   field_name     => 'ocf_service_term',
								label          => 'Years of participation',
								tip            => 'ie: 2002-2009',
								compound_field => 1,
								save_to => { perl => 'return "child_ocf_term_$form_multiplicity"' },
							},
			   ],
			},
		],
	},
	'NOK' => {
		RHTMLO_form     => $nok_form,
		session_hashref => \%session,
		next_form       => { perl => 'finished' },
		elements        => [
			{ subheading_text => 'Next of Kin Contact details' },
			{
			   text =>
				   'Please enter the details of your next of kin whom we would contact in the event of any emergency'
			},
			{  fieldset => 1,
			   legend   => 'Next of Kin Particulars',
			   elements => [ {  field_name     => 'name',
								label          => 'Name',
								tip            => '<u>Nancy</u> Chua',
								compound_field => 0,
								save_to        => 'nok_name',
							 },
							 {  field_name     => 'family_name',
								label          => 'Family Name',
								tip            => 'Nancy <u>Chua</u>',
								compound_field => 0,
								save_to        => 'nok_family_name',
							 },
							 {  field_name     => 'relationship',
								label          => 'Relationship',
								tip            => 'Auntie',
								compound_field => 0,
								save_to        => 'nok_relationship',
							 },
							 {  field_name     => 'phone_number',
								label          => 'Phone Number',
								tip            => '',
								compound_field => 0,
								save_to        => 'nok_phone_number',
							 },
			   ],
			},
		],
	},
};
###
if ( !$forms->{ $session{'current_form'} } ) {
	die $session{'current_form'};
}
###
my $e      = My::Form::Helper::Tools::evalable_code_from_hash(%session);
my $cgi    = $m->cgi_object();
my @params = $cgi->param();
use Data::Dumper;
my $session_string_pre = Data::Dumper::Dumper( \%session );
my $form_advanced;
my $form_reversed;

if ( scalar(@params) ) {
	My::Form::Helper::Tools::init_fields( %{ $forms->{ $session{'current_form'} } },
										  cgi           => $m->cgi_object(),
										  init_from_cgi => 1
	);
	if ( $cgi->param('next_button') ) {
		$form_advanced = next_form( %{ $forms->{ $session{'current_form'} } } );
	} elsif ( $cgi->param('back_button') ) {
		$form_reversed = prev_form( %{ $forms->{ $session{'current_form'} } } );
	}
}
my $session_string_post = Data::Dumper::Dumper( \%session );
###
if ( $form_advanced || $form_reversed ) {
	My::Form::Helper::Tools::init_fields( %{ $forms->{ $session{'current_form'} } },
										  cgi => $m->cgi_object() );
}
